package com.sljy.hzk.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.sljy.hzk.R;
import com.sljy.hzk.entity.UserEntity;
import com.sljy.hzk.ui.LoginActivity;

public class LineEditText extends android.support.v7.widget.AppCompatEditText implements PopupWindow.OnDismissListener ,AdapterView.OnItemClickListener{

    private Paint mPaint;
    private int mLineColor;
    private Drawable mDrawable; // 显示的图
    private Drawable mDrawableLeft; // 显示的图
    private Integer dropResId;
    private Integer upResId;
    private Integer curResId;
    private PopupWindow mPopupWindow; // 点击图片弹出的popWindow对象
    private ListView mPopListView; // popWindow的布局
    private boolean isShowRightDrawable = false;
    private LoginActivity login;
    public LineEditText(Context context) {
        super(context);
    }
    public LineEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        initData(context, attrs);
    }

    public LineEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initData(context, attrs);
    }

    private void initData(Context context, AttributeSet attrs){
        TypedArray attrArrays = context.obtainStyledAttributes(attrs, R.styleable.LineEditText);
        dropResId = R.drawable.drop_down; // 设置下拉图标
        upResId = R.drawable.up_ward;
        curResId = R.drawable.drop_down;
        mPopListView = new ListView(context);
        mPopListView.setOnItemClickListener(this);
        mPopListView.setDivider(new ColorDrawable(Color.BLACK));
        mPopListView.setDividerHeight(1);
        mPaint = new Paint();
        int lenght = attrArrays.getIndexCount();
        for(int i = 0 ; i < lenght; i ++){
            int index = attrArrays.getIndex(i);
            switch (index){
                case R.styleable.LineEditText_lineColorEt:
                    mLineColor =  attrArrays.getColor(index,0xFFF);
                    break;
            }
        }
    }

    /**
     * 我们无法直接给EditText设置点击事件，只能通过按下的位置来模拟点击事件
     * 当我们按下的位置在图标包括图标到控件右边的间距范围内均算有效
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if(isShowRightDrawable){
                if (getCompoundDrawables()[2] != null) {
                    int start = getWidth() - getTotalPaddingRight() + getPaddingRight(); // 起始位置
                    int end = getWidth(); // 结束位置
                    boolean available = (event.getX() > start) && (event.getX() < end);
                    if (available) {
                        setRightResDrawable(upResId);
                        closeSoftInput();
                        showPopWindow();
                        return true;
                    }
                }
            }
        }
        return super.onTouchEvent(event);
    }

    /**
     * 打开PopWindow
     * */
    private void showPopWindow(){
        if(login!= null)
            login.hide(View.GONE);
        mPopupWindow.showAsDropDown(this, 0, -5);
    }

    /**
     * 设置右边的箭头向上或向下
     * */
    private void setRightResDrawable(int resId){
        //判断当前的是否需要显示右边的图片
        if(!isShowRightDrawable)return;
        curResId = resId;
        mDrawable = getResources().getDrawable(resId);
        mDrawable.setBounds(0, 0, mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
        //添加左边图片
       // mDrawableLeft = getResources().getDrawable(R.mipmap.login_user);
        //mDrawableLeft.setBounds(0, 0, mDrawableLeft.getIntrinsicWidth(), mDrawableLeft.getIntrinsicHeight());
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], mDrawable, getCompoundDrawables()[3]);
        //setCompoundDrawables(mDrawableLeft, getCompoundDrawables()[1], mDrawable, getCompoundDrawables()[3]);
    }

    public void setAdapter(BaseAdapter adapter, LoginActivity c ) {
        mPopListView.setAdapter(adapter);
        login = c;
    }

    private void closeSoftInput() {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
    }

    public void setIsDefaultRight(boolean state){
        isShowRightDrawable = state;
        setRightResDrawable(dropResId);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(mLineColor);
        canvas.drawLine(0, getHeight() - 1, getWidth() - 1, getHeight() - 1, mPaint);
    }

    @Override
    public void onDismiss() {
        if(curResId.equals(R.drawable.drop_down))return;
        setRightResDrawable(dropResId);
        if(login!= null)
            login.hide(View.VISIBLE);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object obj = mPopListView.getAdapter().getItem(position);
        UserEntity m = (UserEntity)obj;
        this.setText(m.getAccounts()); // 可能需要你重写item的toString方法
        login.setPasswordEdittext(m.getPassword());
        login.setUserDefaultHead(m.getHeadPic());
        mPopupWindow.dismiss();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            mPopupWindow = new PopupWindow(mPopListView, getWidth(), LinearLayout.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setBackgroundDrawable(null); // 设置popWindow背景颜色
            mPopupWindow.setFocusable(true); // 让popWindow获取焦点
            mPopupWindow.setOnDismissListener(this);
            mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            mPopupWindow.setOutsideTouchable(true);
            //设置监听
            mPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_OUTSIDE && !mPopupWindow.isFocusable()) {
                        //如果焦点不在popupWindow上，且点击了外面，不再往下dispatch事件：
                        //不做任何响应,不 dismiss popupWindow
                        return true;
                    }
                    //否则default，往下dispatch事件:关掉popupWindow，
                    return false;
                }
            });
        }
    }
}
